$(document).ready(function () {
  var table = $('table#table').DataTable({
      initComplete: function(settings, json) {
          $("#table").removeClass('dataTable');
          $("#table").parent().addClass('table-responsive');

          $("#table").parent()
              .css('max-height', $(window).height() - $('#query-area').height() - 260)
              .css('height', 'auto')
              .css('overflow-y', 'visible');

          $("#table").on('change', 'input[type="checkbox"]', function () {
              if($(this).prop('checked')) {
                  $(this).closest('tr').addClass('warning');
              } else {
                  $(this).closest('tr').removeClass('warning');
              }
          });

          // 动态添加搜索条件行间距样式
        $('<style>').text(`#query-area .form-group {margin-bottom: 15px;}`).appendTo('head');

        // 动态添加表头居中样式
        $('<style>').text('#table thead th { text-align: center !important; }').appendTo('head');

        // 添加行点击事件处理
          $("#table tbody").on('click', 'tr', function(e) {
              // 避免点击复选框本身时触发两次
              if (!$(e.target).is('input[type="checkbox"]')) {
                  // 找到当前行的复选框
                  var checkbox = $(this).find('input[type="checkbox"]').first();
                  // 切换复选框状态
                  checkbox.prop('checked', !checkbox.prop('checked'));
                  // 触发change事件以更新行样式
                  checkbox.trigger('change');
              }
          });
      },
    ajax: {
      url: baseUrl + '/datatable',
      data : function(d) {

          var docnum     = $('.search-form').find('input[name="docnum"]').val();
          var lotnum     = $('.search-form').find('input[name="lotnum"]').val();
          var uloc       = $('.search-form').find('input[name="uloc"]').val();
          var sloc       = $('.search-form').find('input[name="sloc"]').val();
          var cnum       = $('.search-form').find('input[name="containnum"]').val();
          var status     = $('.search-form').find('select#status').val();
          var deliverystatus  = $('.search-form').find('select#deliverystatus').val();
          //d.material    = 'KA10010';
          d.category             = 'KIT';
          d.deliveryshipnumber   = docnum;
          d.deliveryterms        = lotnum;
          d.planunloaddoor       = uloc;
          d.deliveryfromplace    = sloc;
          d.containnumber        = cnum;
          d.status               = status;
          d.deliverystatus       = deliverystatus;
		return d;
      }
    },
    order: [
      [9, 'desc']
    ],
    columns: [{
      data: 'id',
      sortable: false,
      defaultContent: '',
      'class': 'text-center',
      render: function (data, type, row, meta) {
          return '<input type="checkbox" name="ids" value="' + data + '" style="transform: scale(1.5);"/>'
      }


     },{
        'class': 'text-center',
      name: 'documentNumber',
      data: 'documentNumber'
    },{
        'class': 'text-center',
      name: 'deliveryContainerNum',
      data: 'deliveryContainerNum'
    },{
        'class': 'text-center',
         name: 'deliveryShipNum',
         data: 'deliveryShipNum',
        render: function (data, type, row, meta) {
            return `<a hfre="#" style="text-decoration: underline" onclick="showSodetail('${row.deliveryShipNum}')">${row.deliveryShipNum}</a>`;
        }
    },{
        'class': 'text-center',
      name: 'deliveryTerms',
      data: 'deliveryTerms'
    },{
        'class': 'text-center',
      name: 'planUnloadPlace',
      data: 'planUnloadPlace'
    },{
        'class': 'text-center',
        name: 'planUnloadDoor',
        data: 'planUnloadDoor'
    },{
        'class': 'text-center',
        name: 'deliveryFromPlace',
        data: 'deliveryFromPlace'
    },{
        'class': 'text-center',
        name: 'createSource',
        data: 'createSource'
    },{
        'class': 'text-center',
        name: 'createdDate',
        data: 'createdDate'
    },{
        'class': 'text-center',
        name: 'deliveryLastStatus',
        data: 'deliveryLastStatus',
        render: function (data, type, row, meta) {
            if ((data==null) || (data=='')) return '码盘中';
            if (data=='0000') return '码盘中';
            if (data=='0150') return '码盘中';
            if (data=='0210') return '上架中';
            if (data=='0880') return '完成';
            if (data=='0850') return '取消';
        }
    }, {
      data: "id",
      defaultContent: '',
      sortable: false,
      'class': 'text-center',
      render: function (data, type, row, meta) {
        return ('<div class="btn-group">' +
          '<a  class="btn btn-default btn-xs" title="修改" href="' + baseUrl + '/edit/' + row.id + '"><i class="fa fa-edit"></i></a>' +
          '<a class="btn btn-default btn-xs del" title="删除" href="#"><i class="fa fa-trash-o"></i></a>' +
          '</div>' +
          '&nbsp;&nbsp;');
      }
    }]
  });

  table.on('click', '.del', function () {
    var id = table.row($(this).parents('tr')).data().id;
    $("#delForm #ids").val(id);
    if (id) {
      bootbox.confirm("确定要删除数据吗?", function (result) {
        if (result) {
          $("#delForm").submit();
        }
      });
    }
  });
  $(".btn.delAll").on("click", function (e) {
    var ids = [];
    $('#table>tbody input:checked').each(function (i, item) {
      ids.push($(item).val());
    });
    $("#delForm #ids").val(ids.join(","));
    if (ids.length > 0) {
      bootbox.confirm("确定要删除选中的数据吗?", function (result) {
        if (result) {
          $("#delForm").submit();
        }
      });
    } else {
      bootbox.alert("请选择要删除的数据.");
    }
  });

  $(".btn.recvAll").on("click", function (e) {
    var ids = [];
    $('#table>tbody input:checked').each(function (i, item) {
      ids.push($(item).val());
    });
    $("#receiveForm #ids").val(ids.join(","));
    if (ids.length > 0) {
        bootbox.confirm("确定要对选中的单证进行整单收货吗?", function (result) {
        if (result) {
          $("#receiveForm").submit();
        }
      });
    } else {
      bootbox.alert("请选择要收货的单证.");
    }
  });

  $(".btn.printLabel").on("click", function (e) {
    var ids = [];
    $('#table>tbody input:checked').each(function (i, item) {
        ids.push($(item).val());
    });
    $("#printlabelForm #ids").val(ids.join(","));
    if (ids.length > 0) {
        bootbox.confirm("确定要对选中的单证进行打印吗?", function (result) {
            if (result) {
                $("#printlabelForm").submit();
            }
        });
    } else {
        bootbox.alert("请选择要打印的单证.");
    }
  });

  $(".btn.closeAll").on("click", function (e) {
    var ids = [];
    $('#table>tbody input:checked').each(function (i, item) {
      ids.push($(item).val());
    });
    $("#closeForm #ids").val(ids.join(","));
    if (ids.length > 0) {
      bootbox.confirm("确定要关闭选中的数据吗?", function (result) {
        if (result) {
          $("#closeForm").submit();
        }
      });
    } else {
      bootbox.alert("请选择要关闭的数据.");
    }
  });


  table.on('click', '.enable', function () {
    var that = this;
    var data = table.row($(this).parents('tr')).data();
    var id = data.id;
    var enabled = data.enabled;
    bootbox.confirm("确定要更新选中的数据吗?", function(resul) {
	if (resul) {
	    $.get(baseUrl + "/enable", {
	      enabled: !enabled,
	      ids: id
	    }, function (res) {
	      if (res) {
	        data.enabled = !enabled;
	        $(that).find("i").removeClass("fa-" + (enabled ? "check-" : "") + "square-o").addClass("fa-" + (!enabled ? "check-" : "") + "square-o");
	        toastr.info('操作成功!');
	      }

	    });
	}});
  });

  $('.search-form').on("submit", function (e) {
    table.draw();
    //阻止表单submit
    return false;
  });

});


function showSodetail(deliveryShipNum) {
    console.log(deliveryShipNum);
    var $modal = $("#detailModal");
    $modal.find("iframe").attr("src", `${rootUrl}/inbound/kitdocline/${deliveryShipNum}`);
    $modal.modal('show');
}
